package cn.itsource.service.impl;

import cn.itsource.api.LoginRemoteApi;
import cn.itsource.constants.ErrorCode;
import cn.itsource.pojo.domain.Driver;
import cn.itsource.mapper.DriverMapper;
import cn.itsource.pojo.domain.Login;
import cn.itsource.pojo.dto.DriverRegisterDto;
import cn.itsource.result.JSONResult;
import cn.itsource.service.IDriverService;
import cn.itsource.template.WeChatTemplate;
import cn.itsource.utils.IdUtil;
import cn.itsource.utils.NameUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 司机对象 服务实现类
 * </p>
 *
 * @author luoc
 * @since 2024-08-31
 */
@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements IDriverService {

    @Autowired
    private WeChatTemplate weChatTemplate;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private LoginRemoteApi loginRemoteApi;

    @Override
    public JSONResult weChatRegister(DriverRegisterDto registerDto) {
        // String phoneNumber = weChatTemplate.getPhoneNumber(phoneCode);
        // System.out.println("phoneNumber = " + phoneNumber);
        String openId = weChatTemplate.getOpenId(registerDto.getCode());
        LambdaQueryWrapper<Driver> wrapper = new LambdaQueryWrapper<Driver>().eq(Driver::getOpenId,openId);
        Driver driver1 = driverMapper.selectOne(wrapper);
        if (driver1 == null) {
            Driver driver = new Driver();
            driver.setId(IdUtil.getId());
            driver.setOpenId(openId);
            driver.setCreateTime(new Date());
            Login login = getLogin(openId);
            JSONResult register = loginRemoteApi.register(login);
            if (register.getCode() == 200){
                super.save(driver);
                return JSONResult.success();
            }
            return register;
        }
        return JSONResult.error(ErrorCode.PARAM_PHONE_EXIST);
    }

    private static Login getLogin(String openId) {
        Login loginUser = new Login();
        loginUser.setUsername(NameUtil.getName());
        loginUser.setId(IdUtil.getId());
        loginUser.setPassword("123456");
        loginUser.setType(1);
        loginUser.setEnabled(true);
        loginUser.setAdmin(false);
        loginUser.setNickName(loginUser.getUsername());
        loginUser.setOpenId(openId);
        loginUser.setName(loginUser.getUsername());
        loginUser.setCreateTime(new Date());
        return loginUser;
    }
}
